<template>
  <div>
    <el-dialog
      title="编辑菜单"
      :visible.sync="modalVisible"
      width="50%"
      @close="closeModal"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-form-item label="菜单类型" size="mini">
          <!-- type (integer, optional): 类型(1:菜单,2:按钮),后台生成 -->
          <el-radio-group v-model="form.type" @change="changeRadio">
            <el-radio :label="0">顶级目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 菜单 -->
        <div v-if="form.type===1">
          <el-form-item label="上级菜单" size="mini" prop="pid">
            <el-cascader
              :options="getRenderList"
              :props="props"
              clearable
              @change="chooseMenu($event,0)"
            />
          </el-form-item>
        </div>
        <!-- 顶级目录 -->
        <div v-if="form.type!==2">
          <el-form-item label="路由名称" size="mini" prop="name">
            <el-input v-model="form.name" placeholder="前端路由Name,唯一" size="mini" />
          </el-form-item>
          <el-form-item label="路径" size="mini" prop="path">
            <el-input v-model="form.path" placeholder="前端路由path,忽略父节点路径" size="mini" />
          </el-form-item>
          <el-form-item label="组件路径" size="mini" prop="component">
            <el-input v-model="form.component" placeholder="前端路由组件路径,比如：@/views/foo/foo.vue" size="mini" />
          </el-form-item>
          <el-form-item label="组件路径" size="mini">
            <el-input v-model="form.redirect" placeholder="redirect属性" size="mini" />
          </el-form-item>
          <el-form-item label="排序" size="mini">
            <el-input-number v-model="form.sort" size="mini" :controls="true" controls-position="both" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="是否隐藏" size="mini">
                <el-radio v-model="form.hidden" :label="false">否</el-radio>
                <el-radio v-model="form.hidden" :label="true">是</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="是否展开" size="mini">
                <el-radio v-model="form.alwaysShow" :label="false">否</el-radio>
                <el-radio v-model="form.alwaysShow" :label="true">是</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="meta属性" size="normal">
            <div style="width:100%;">
              <el-row v-for="(item,index) in meta" :key="item.key" :gutter="0">
                <el-col :span="10" :offset="0">
                  <el-input v-model="item.key" placeholder="meta的key" size="mini" clearable />
                </el-col>
                <el-col :span="10" :offset="1">
                  <el-input v-model="item.value" :placeholder="item.placeholder" size="mini" clearable />
                </el-col>
                <el-col :span="2" :offset="1">
                  <i class="el-icon-plus" @click="addOneMeta" />
                  <i v-if="index>=2" style="color:red;margin-left:10px;" class="el-icon-minus" @click="subOneMeta(index)" />
                </el-col>
              </el-row>
            </div>
          </el-form-item>

        </div>

        <!-- 按钮 -->
        <div v-if="form.type===2">
          <el-form-item label="所在页面" size="mini" prop="pid">
            <el-cascader
              :options="getRenderList"
              :props="props"
              clearable
              @change="chooseMenu($event,1)"
            />
          </el-form-item>
          <el-form-item label="按钮名称" size="mini" prop="title">
            <el-input v-model="form.title" placeholder="按钮名称，比如：新增" size="mini" clearable />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="排序" size="mini">
                <el-input-number v-model="form.sort" size="mini" :controls="true" controls-position="both" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="层级" size="mini">
                <el-input-number v-model="form.level" size="mini" :controls="true" controls-position="both" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="权限标识" size="mini" prop="permissionValue">
            <el-input
              v-model="form.permissionValue"
              type="textarea"
              :rows="3"
              placeholder="按钮权限标识:比如:productList:list"
            />
          </el-form-item>

        </div>
      </el-form>

      <span slot="footer">
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import _ from 'lodash'
import {
  save as saveApi
} from '@/api/auth/resource'
export default {
  name: 'MenuDialog',
  props: {
    menuList: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      modalVisible: false,
      form: {
        type: 0,
        sort: 0,
        level: 0,
        hidden: true,
        alwaysShow: false,
        pid: ''
      },
      meta: [
        {
          key: 'title',
          value: '未命名',
          placeholder: '比如:商品管理'
        },
        {
          key: 'icon',
          value: 'el-icon-menu',
          placeholder: '比如:el-icon-menu'
        }
      ],
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请输入路由名称' }],
        path: [{ required: true, trigger: 'blur', message: '请输入路由路径名称' }],
        component: [{ required: true, trigger: 'blur', message: '请输入组件路径名称' }],
        permissionValue: [{ required: true, trigger: 'blur', message: '请输入按钮的权限标识' }],
        title: [{ required: true, trigger: 'blur', message: '请输入按钮的名称' }],
        pid: [{ required: true, trigger: 'blur', message: '请选择所在页面名称/上级菜单' }]
      },
      props: {
        checkStrictly: true,
        expandTrigger: 'hover',
        emitPath: false,
        label: 'title',
        value: 'id',
        disabled: 'disabled'
      }
    }
  },
  computed: {
    // 重写menuList值，为了不改变原数组
    getRenderList() {
      var menu = _.cloneDeep(this.menuList)
      this.handleArray(menu)
      console.log('处理后的menu==>', menu)
      return menu
    }
  },
  created() {

  },
  methods: {
    // 改变上层单选按钮
    changeRadio(e) {
      this.form = this.$options.data().form
      this.form.type = e
    },
    // 改变菜单选择
    chooseMenu(e, id) {
      if (id) { // 按钮
        this.form.pid = e
      } else { // 菜单
        this.form.pid = e
      }
    },
    // 处理原始menu数组将其空的children数组删除，并将type为2的元素增加disabled属性，且值为true
    handleArray(arr) {
      arr.forEach(item => {
        if (item.type === 2) {
          item.disabled = true
        }

        if (item.children && item.children.length === 0) {
          delete item.children
        } else {
          this.handleArray(item.children)
        }
      })
    },
    // 减少一个meta属性
    subOneMeta(index) {
      this.meta.splice(index, 1)
    },
    // 增加一个meta属性
    addOneMeta() {
      var obj = {
        key: '',
        value: '',
        placeholder: ''
      }
      this.meta.push(obj)
    },
    // 打开弹框
    openModal() {
      this.modalVisible = true
      this.form = this.$options.data().form
    },
    // 关闭弹框
    closeModal() {
      this.modalVisible = false
    },
    // 部分校验表格
    getRuleResult(arr) {
      var errorArr = []
      this.$refs.form.validateField(arr, error => {
        errorArr.push(error)
      })
      for (var i = 0; i < errorArr.length; i++) {
        if (errorArr[i]) {
          this.$message.error(errorArr[i])
          return false
        }
      }
      return true
    },
    formatMeta(arr) {
      var obj = {}
      arr.forEach(item => {
        obj[item.key] = item.value
      })
      return JSON.stringify(obj)
    },
    // 保存
    save() {
      var arr = []
      if (this.form.type === 0) {
        arr = ['name', 'path', 'component']
        this.form.type = 1
        this.level = 0
        this.meta = this.formatMeta(this.meta)
      } else if (this.form.type === 2) {
        arr = ['permissionValue', 'pid', 'title']
        this.form.type = 2
        delete this.form.hidden
      } else {
        arr = ['name', 'path', 'component', 'pid']
        this.form.type = 1
        this.meta = this.formatMeta(this.meta)
      }
      if (this.getRuleResult(arr)) {
        console.log('this.form==>', this.form)
        saveApi(this.form)
          .then(res => {
            const { success, message } = res
            if (success) {
              this.modalVisible = false
              this.$message.success('操作成功！')
              this.$emit('regetMenuList')
            } else {
              this.$message.error(message)
            }
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
 ::v-deep label{
    font-weight: 700;
}
</style>
